import React, {useState} from 'react';
import {Alert, Image, Linking, Modal, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import {getImgUrl} from "../../../utils/ComFunction";
import BigImageContainer from "../../../components/Tool/BigImageContainer";
import HttpUtils from "../../../utils/HttpUtils";
import HttpUrls from "../../../utils/HttpUrls";

const SeekItemView = ({item, buyerId, onPress, navigation, isDetail = false, onPressDel, onPressUpDown, onPressEdit}) => {
    const [showFullRemarks, setShowFullRemarks] = useState(0);
    const [showBigImageContainer, setShowBigImageContainer] = useState(false);
    const [currImgIndex, setCurrImgIndex] = useState(0);

    const imgUrls = item.purchaseImages?.map(item => {
        return {
            url: getImgUrl(item)
        }
    });

    // 点击图片显示大图
    const handleImagePress = (tag) => {
        setShowBigImageContainer(tag);
    };
    const handleCurrImgIndexPress = (index) => {
        setCurrImgIndex(index);
    };

    // 1. 初始化状态
    const [measuredLines, setMeasuredLines] = useState(0);

    // 2. 文本布局测量函数
    const handleTextLayout = (event) => {
        setMeasuredLines(event.nativeEvent.lines.length);
    };

    // 添加拨打买手电话号码记录
    const addPhoneHistory = (buyerId) =>{
        HttpUtils.postRequest(HttpUrls.addPhoneHistory, { buyerId: buyerId, type: 1 })
            .then(result => {
                console.log('addPhoneHistory', result)
            }).finally(e => {
        })
    }

    return (
        <TouchableOpacity activeOpacity={0.7} style={styles.listItem} onPress={onPress}>
            <View style={styles.buyInfo}>
                <View style={styles.avatarContainer}>
                    {item.buyerInfo?.avatar ? (
                        <Image
                            style={styles.avatar}
                            source={{
                                uri: getImgUrl(item.buyerInfo?.avatar),
                            }}
                        />
                    ) : (
                        <Image
                            style={styles.avatar}
                            source={require('source/image/seekCenter/default_avatar.png')}
                        />
                    )}
                </View>

                <View style={styles.userInfo}>
                    <Text numberOfLines={1} style={styles.nameRow}>
                        <Text style={styles.nameText}>{item.buyerInfo?.fullname || '未命名'}</Text>
                        <View style={{width: 5}} />
                        <TouchableOpacity activeOpacity={0.7} onPress={() => {
                            navigation.navigate('CompanyInfoPage', {
                                merchantId: item.buyerInfo?.merchantId,
                            });
                        }}>
                            <Text style={styles.merchantText}>
                                @{item.buyerInfo?.merchantAbbreviation || '门店信息不存在'}
                            </Text>
                        </TouchableOpacity>

                    </Text>
                    <View style={styles.timeTextBox}>
                        <Text style={styles.timeText}>{item?.timeShow || '未知'}</Text>
                        <View style={{width: 1, height: 10, marginHorizontal: 5, borderLeftWidth:1, borderColor:'#666'}}></View>
                        <Text style={styles.timeText}>{item.buyerInfo?.provinceName} {item.buyerInfo?.cityName}</Text>
                    </View>
                </View>

                {buyerId === 0 ? (
                        <View>
                            <View style={styles.actionButtonSelect}>
                                <TouchableOpacity activeOpacity={0.7} onPress={()=> {
                                    // 拨打电话
                                    const url = `tel:${item.buyerInfo?.phone}`;
                                    Linking.canOpenURL(url).then(supported => {
                                        if (!supported) {
                                            return Alert.alert('提示', `您的设备不支持该功能，请手动拨打 ${item.buyerInfo?.phone}`, [
                                                { text: '确定' }
                                            ]);
                                        }else {
                                            addPhoneHistory(item.buyerInfo?.buyerId)
                                        }
                                        return Linking.openURL(url);
                                    }).catch(err => Alert(err));
                                }}>
                                    <Text style={styles.actionText}>电话</Text>
                                </TouchableOpacity>
                                <Text style={{marginLeft: 5, marginRight: 5, color: '#E5E5E5'}}>|</Text>
                                <TouchableOpacity activeOpacity={0.7} onPress={()=> {
                                    navigation.navigate('SeekingCarPage', {
                                        id: item.id,
                                        merchantId: item.buyerInfo?.merchantId || null,
                                        userId: item.buyerInfo?.userId || null,
                                    })
                                }}>
                                    <Text style={styles.actionText}>推荐车</Text>
                                </TouchableOpacity>
                            </View>
                            <View>
                                <Text style={{fontSize: 10, color: '#ED542E', textAlign: 'center'}}>匹配到{item.carMatchCount || 0}辆车</Text>
                            </View>
                        </View>
                    )
                    : null
                }

                {item.buyerId === buyerId ? (
                        <View>
                            {item.status === 2 || item.status === 3 ? (
                                <Text style={[
                                    styles.expiredText, {color: '#ED542E'}
                                ]}>{item.statusText || '未知'}</Text>
                            ) : null}
                            <Text style={[styles.expiredText, {marginTop: 5, color: '#ED542E'}]}>匹配到{item.carMatchCount || 0}辆车 | 咨询: {item?.contactNum || 0} 人</Text>
                        </View>
                    )
                    : null
                }

            </View>
            {/* 收车信息 */}
            <View style={{paddingHorizontal: 10, paddingVertical: 10}}>
                <Text numberOfLines={1}
                      ellipsizeMode="tail"
                      style={{fontSize: 16,color: '#333333', fontWeight: 'bold'}}>{item?.title}</Text>
                <View style={{width:'100%', marginTop: 5 }}>
                    {
                        isDetail
                            ?
                            <Text
                                style={{ fontSize: 14, color: '#333333'}}
                            >
                                {item.remarks}
                            </Text>
                            :
                            <Text
                                numberOfLines={showFullRemarks ? 0 : 2}
                                ellipsizeMode="tail"
                                onTextLayout={handleTextLayout}
                                style={{ fontSize: 14, color: '#333333', flex: 1 }}>
                                {item.remarks}
                            </Text>
                    }
                    {measuredLines > 2 && !isDetail ? (
                        <Text
                            onPress={() => setShowFullRemarks(!showFullRemarks)}
                            style={{ color: '#1E90FF' }}>
                            {showFullRemarks ? ' 收起' : ' 全文'}
                        </Text>
                    ) : null}
                    {/*{measuredLines > 2 && !isDetail ? (*/}
                    {/*    <TouchableOpacity onPress={() => setShowFullRemarks(!showFullRemarks)}>*/}
                    {/*        <Text style={{ color: '#1E90FF', fontSize: 14, marginLeft: 5 }}>*/}
                    {/*            {showFullRemarks ? '收起' : '全文'}*/}
                    {/*        </Text>*/}
                    {/*    </TouchableOpacity>*/}
                    {/*) : null}*/}
                </View>
                {/*<Text style={{color: '#666', fontSize: 14, marginTop: 5}}>求购车型: {item?.carModelString || '不限'}</Text>*/}
                {/*<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>*/}
                {/*    <Text numberOfLines={1} style={{width: '50%', color: '#666', fontSize: 14}}>求购地区: {item?.carAreaString || '不限'}</Text>*/}
                {/*    <Text numberOfLines={1} style={{width: '50%', color: '#666', fontSize: 14}}>所在地: {item.buyerInfo?.provinceName} {item.buyerInfo?.cityName}</Text>*/}
                {/*</View>*/}
                {item.purchaseTags?.length > 0 && (
                    <View style={{backgroundColor: '#F9F9F9', borderRadius: 4, flexDirection: 'row', flexWrap: 'wrap', padding: 5, marginTop: 10}}>
                        {item.purchaseTags?.map((tag, tagIndex) => {
                            return (
                                <Text style={{color: '#345F94', fontSize: 14, marginRight: 5}}># {tag}</Text>
                            );
                        })}
                    </View>
                )}
                <View style={styles.imageGridContainer}>
                    {item.purchaseImages?.map((tag, tagIndex) => (
                        <TouchableOpacity
                            key={item.id + tagIndex}
                            onPress={() => {
                                handleCurrImgIndexPress(tagIndex)
                                handleImagePress(true)
                            }}
                            style={styles.imageGridItem}
                        >
                            <Image
                                style={styles.imageGrid}
                                source={{
                                    uri: getImgUrl(tag),
                                }}
                            />
                        </TouchableOpacity>
                    ))}
                </View>
            </View>

            {/* 操作按钮 */}
            {item.buyerId === buyerId ? (
                <View style={styles.actionsContainer}>
                    <TouchableOpacity style={styles.actionButton} activeOpacity={0.7} onPress={onPressUpDown}>
                        <Image
                            style={styles.actionImage}
                            source={require('source/image/out_garage_icon.png')}
                        />
                        {/*<Text style={styles.actionButtonText}>上架/下架</Text>*/}
                        <Text style={styles.actionButtonText}>{item.status === 1 ? '下架' : '上架'}</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.actionButton} activeOpacity={0.7} onPress={onPressEdit}>
                        <Image
                            style={styles.actionImage}
                            source={require('source/image/edit_car_icon.png')}
                        />
                        <Text style={styles.actionButtonText}>编辑</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.actionButton} activeOpacity={0.7} onPress={onPressDel}>
                        <Image
                            style={styles.actionImage}
                            source={require('source/image/delete_car_icon.png')}
                        />
                        <Text style={styles.actionButtonText}>删除</Text>
                    </TouchableOpacity>
                </View>
            ) : null}

            {
                showBigImageContainer ?
                    <Modal
                        visible={showBigImageContainer}
                        transparent={true}
                        onRequestClose={() => handleImagePress(false)}
                    >
                        <BigImageContainer
                            idx={currImgIndex}
                            images={imgUrls}
                            closeHandler={(index) => {
                                handleCurrImgIndexPress(index)
                                handleImagePress(false)
                            }}
                        />
                    </Modal>
                    :
                    null
            }

        </TouchableOpacity>
    );
};

const styles = StyleSheet.create({
    // 列表信息
    listItem: {
        backgroundColor: '#ffffff',
        flexDirection: 'column',
    },
    buyInfo: {
        flexDirection: 'row',
        justifyContent: 'flex-start',
        paddingHorizontal: 8,
        paddingVertical: 8,
        alignItems: 'center',
        borderBottomColor: '#eee',
        borderBottomWidth: 0.5,
    },
    avatarContainer: {
        alignItems: 'center',
        justifyContent: 'center',
        marginRight: 7, // 添加右边距
    },
    avatar: {
        width: 42,
        height: 42,
        borderRadius: 50,
    },
    userInfo: {
        flex: 1, // 占据剩余空间
        justifyContent: 'center',
        paddingHorizontal: 5,
    },
    nameRow: {
        flexDirection: 'row',
    },
    nameText: {
        color: '#333',
        fontSize: 14,
    },
    merchantText: {
        color: '#FFA500',
        fontSize: 12,
    },
    timeTextBox: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    timeText: {
        fontSize: 12,
        color: '#666',
    },
    actionButtonSelect: {
        borderWidth: 1,
        borderColor: '#E5E5E5',
        // width: 120,
        height: 30,
        borderRadius: 15,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: 10,
    },
    actionText: {
        fontSize: 14,
        color: '#333',
    },

    expiredText: {
        fontSize: 12,
        color: '#333333',
    },

    // 求购item
    actionsContainer: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        backgroundColor: '#fff',
        paddingBottom: 10
    },
    actionButton: {
        flexDirection: 'row',
        padding: 5,
    },
    actionButtonText: {
        fontWeight: 'bold',
        fontSize: 14,
        color: '#333333',
        marginLeft: 5,
    },
    actionImage: {
        width: 20,
        height: 20,
    },

    // 图片
    imageGridContainer: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        marginTop: 10,
    },
    imageGridItem: {
        width: '33.333%', // 每行三张图片
        aspectRatio: 1, // 正方形比例
        padding: 2,
    },
    imageGrid: {
        width: '100%',
        height: '100%',
        borderRadius: 4,
    },


});

export default SeekItemView;